{% extends "base.html" %}

{% block title %}收费记录{% endblock %}

{% block styles %}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<style>
.select2-container {
    width: 100% !important;
}
.number-cell {
    text-align: right;
}
</style>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>收费记录</h2>
    <div>
        <button class="btn btn-secondary me-2" type="button" data-bs-toggle="collapse" data-bs-target="#filterForm">
            过滤条件 <i class="bi bi-funnel"></i>
        </button>
        <a href="{{ url_for('add_payment') }}" class="btn btn-primary me-2">添加收费记录</a>
        <a href="{{ url_for('add_refund') }}" class="btn btn-warning me-2">添加退费记录</a>
        <a href="{{ url_for('export_payments') }}?{{ request.query_string.decode() }}" class="btn btn-success">
            <i class="bi bi-download me-1"></i>导出
        </a>
    </div>
</div>

<div class="collapse mb-4" id="filterForm">
    <div class="card card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label for="student" class="form-label">学生</label>
                <input type="text" class="form-control" id="student" name="student" value="{{ request.args.get('student', '') }}">
            </div>
            <div class="col-md-3">
                <label for="class_name" class="form-label">班级</label>
                <select class="form-select" id="class_name" name="class_name">
                    <option value="">全部</option>
                    {% for class in classes %}
                    <option value="{{ class.grade }} {{ class.year }} {{ class.semester }}" 
                            {% if request.args.get('class_name') == class.grade + ' ' + class.year + ' ' + class.semester %}selected{% endif %}>
                        {{ class.grade }} {{ class.year }} {{ class.semester }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label for="year" class="form-label">年度</label>
                <select class="form-select" id="year" name="year">
                    <option value="">全部</option>
                    {% for year in years %}
                    <option value="{{ year[0] }}" {% if request.args.get('year') == year[0] %}selected{% endif %}>
                        {{ year[0] }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label for="semester" class="form-label">学期</label>
                <select class="form-select" id="semester" name="semester">
                    <option value="">全部</option>
                    {% for semester in semesters %}
                    <option value="{{ semester.name }}" {% if request.args.get('semester') == semester.name %}selected{% endif %}>
                        {{ semester.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label for="project" class="form-label">收费项目</label>
                <select class="form-select" id="project" name="project">
                    <option value="">全部</option>
                    {% for project in projects %}
                    <option value="{{ project.name }}" {% if request.args.get('project') == project.name %}selected{% endif %}>
                        {{ project.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label for="account" class="form-label">收款账号</label>
                <select class="form-select" id="account" name="account">
                    <option value="">全部</option>
                    {% for account in accounts %}
                    <option value="{{ account.account }}" {% if request.args.get('account') == account.account %}selected{% endif %}>
                        {{ account.account }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-3">
                <label for="start_date" class="form-label">起始日期</label>
                <input type="date" class="form-control" id="start_date" name="start_date" 
                       value="{{ request.args.get('start_date', min_date.strftime('%Y-%m-%d')) }}">
            </div>
            <div class="col-md-3">
                <label for="end_date" class="form-label">结束日期</label>
                <input type="date" class="form-control" id="end_date" name="end_date" 
                       value="{{ request.args.get('end_date', max_date.strftime('%Y-%m-%d')) }}">
            </div>
            <div class="col-md-3">
                <label for="min_amount" class="form-label">最小金额</label>
                <input type="number" step="0.01" class="form-control" id="min_amount" name="min_amount" 
                       value="{{ request.args.get('min_amount', '%.2f'|format(min_amount)) }}">
            </div>
            <div class="col-md-3">
                <label for="max_amount" class="form-label">最大金额</label>
                <input type="number" step="0.01" class="form-control" id="max_amount" name="max_amount" 
                       value="{{ request.args.get('max_amount', '%.2f'|format(max_amount)) }}">
            </div>
            <div class="col-12">
                <button type="submit" class="btn btn-primary">搜索</button>
                <a href="{{ url_for('list_payments') }}" class="btn btn-secondary">重置</a>
            </div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>日期</th>
                <th>学生</th>
                <th>班级</th>
                <th>年度</th>
                <th>学期</th>
                <th>收费项目</th>
                <th>金额</th>
                <th>收款账号</th>
                <th>摘要</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for payment in payments %}
            <tr {% if loop.index > 6 %}class="payment-row" style="display: none;"{% endif %}>
                <td>{{ payment.date.strftime('%Y-%m-%d') }}</td>
                <td>{{ payment.student }}</td>
                <td>{{ payment.class_name }}</td>
                <td>{{ payment.year }}</td>
                <td>{{ payment.semester }}</td>
                <td>{{ payment.project }}</td>
                <td>{{ "%.2f"|format(payment.amount) }}</td>
                <td>{{ payment.account }}</td>
                <td>{{ payment.summary or '' }}</td>
                <td>
                    <a href="{{ url_for('edit_payment', id=payment.id) }}" class="btn btn-sm btn-warning">编辑</a>
                    <form action="{{ url_for('delete_payment', id=payment.id) }}" method="POST" class="d-inline">
                        <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('确定要删除这条收费记录吗？')">删除</button>
                    </form>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% if payments|length > 6 %}
    <div class="text-center mt-3">
        <button type="button" class="btn btn-outline-primary" id="toggleButton" onclick="togglePayments()">
            展开更多 <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    {% endif %}
</div>

<!-- 聚合统计表格 -->
<div class="table-responsive mt-4">
    <div class="d-flex justify-content-between align-items-center mb-2">
        <h4 class="mb-0">收费汇总统计</h4>
        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="transposeSummaryTable()">
            <i class="bi bi-arrow-repeat"></i> 转置
        </button>
    </div>
    <table class="table table-striped" id="summaryTable">
        <thead>
            <tr>
                <th class="fw-bold">收款账号</th>
                {% for project in projects %}
                <th class="number-cell">{{ project.name }}</th>
                {% endfor %}
                <th class="table-info number-cell">小计</th>
            </tr>
        </thead>
        <tbody>
            {% for account in accounts %}
            <tr>
                <td class="fw-bold">{{ account.account }}</td>
                {% for project in projects %}
                {% set amount = payments|selectattr('account', 'eq', account.account)|selectattr('project', 'eq', project.name)|map(attribute='amount')|sum %}
                <td class="number-cell">{{ "%.2f"|format(amount) if amount > 0 else '' }}</td>
                {% endfor %}
                {% set account_total = payments|selectattr('account', 'eq', account.account)|map(attribute='amount')|sum %}
                <td class="table-info number-cell">{{ "%.2f"|format(account_total) if account_total > 0 else '' }}</td>
            </tr>
            {% endfor %}
            <tr class="table-info fw-bold">
                <td>合计</td>
                {% for project in projects %}
                {% set project_total = payments|selectattr('project', 'eq', project.name)|map(attribute='amount')|sum %}
                <td class="number-cell">{{ "%.2f"|format(project_total) if project_total > 0 else '' }}</td>
                {% endfor %}
                {% set total = payments|map(attribute='amount')|sum %}
                <td class="number-cell">{{ "%.2f"|format(total) if total > 0 else '' }}</td>
            </tr>
        </tbody>
    </table>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('#class_name').select2({
        theme: 'bootstrap-5',
        placeholder: '请选择班级',
        allowClear: true
    });
});

function togglePayments() {
    const rows = document.getElementsByClassName('payment-row');
    const button = document.getElementById('toggleButton');
    const isExpanded = rows[0].style.display !== 'none';
    
    for (let row of rows) {
        row.style.display = isExpanded ? 'none' : '';
    }
    
    button.innerHTML = isExpanded ? 
        '展开更多 <i class="bi bi-chevron-down"></i>' : 
        '收起 <i class="bi bi-chevron-up"></i>';
}

function transposeSummaryTable() {
    const table = document.getElementById('summaryTable');
    const rows = Array.from(table.rows);
    
    // 获取原始数据
    const data = rows.map(row => Array.from(row.cells).map(cell => ({
        text: cell.textContent.trim(),
        isHeader: cell.tagName === 'TH',
        isInfo: cell.classList.contains('table-info'),
        isNumber: cell.classList.contains('number-cell'),
        isBold: cell.classList.contains('fw-bold')
    })));
    
    // 转置数据
    const transposed = data[0].map((_, colIndex) => data.map(row => row[colIndex]));
    
    // 清空表格
    while (table.firstChild) {
        table.removeChild(table.firstChild);
    }
    
    // 创建新的表头和表体
    const thead = document.createElement('thead');
    const tbody = document.createElement('tbody');
    
    // 填充转置后的数据
    transposed.forEach((row, rowIndex) => {
        const tr = document.createElement('tr');
        if (rowIndex === transposed.length - 1) {
            tr.classList.add('table-info', 'fw-bold');
        }
        
        row.forEach(cell => {
            const el = cell.isHeader ? document.createElement('th') : document.createElement('td');
            el.textContent = cell.text;
            if (cell.isInfo) el.classList.add('table-info');
            if (cell.isNumber || (!cell.isHeader && rowIndex > 0)) el.classList.add('number-cell');
            if (cell.isBold) el.classList.add('fw-bold');
            tr.appendChild(el);
        });
        
        if (rowIndex === 0) {
            thead.appendChild(tr);
        } else {
            tbody.appendChild(tr);
        }
    });
    
    table.appendChild(thead);
    table.appendChild(tbody);
}
</script>
{% endblock %} 